package by.jtraining.london.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.jtraining.london.model.Student;
import by.jtraining.london.repo.StudentRepository;
import by.jtraining.london.service.StudentService;

import com.google.inject.Inject;
import com.google.inject.persist.Transactional;

public class StudentServiceImpl extends
		GenericServiceImpl<Student, Long, StudentRepository> implements
		StudentService {
	private static final Logger LOG = LoggerFactory
			.getLogger(StudentServiceImpl.class);
	@Inject
	public StudentServiceImpl(StudentRepository studentRepository) {
		super(studentRepository);
	}

	@Transactional
	@Override
	public void add(Student student) {
		LOG.debug("Trying to add student{}", student);
		repo.add(student);
		LOG.debug("Added next student{}", student);
	}
	
	@Transactional
	@Override
	public boolean isUploadApplicationFormForUser(long id){
		LOG.info("Is upload form or not");
		return repo.isUploadApplicationFormForUser(id);
	}
	@Transactional
	@Override
	public List<Student> search(String firstName,String lastName, String email, String phone, String registrDateStart, String registrDateEnd){
		List<String> params=makeListParametrsForQuery(firstName,lastName, email, phone, registrDateStart, registrDateEnd);
		String queryTerm=makeQueryForSearch(params);
		return repo.search(queryTerm);
	}
	
	 private List<String> makeListParametrsForQuery(String firstName,String lastName, String email, String phone, String registrDateStart, String registrDateEnd){
		 List<String> listParametrsForQuery=new ArrayList<String>();
		 if(firstName.length()>0){
			 listParametrsForQuery.add("firstName like '"+firstName+"' AND ");
			 }
			 if(lastName.length()>0){	 
			 listParametrsForQuery.add("lastName like '"+lastName+"' AND ");
			 }
			 if(email.length()>0){
			 listParametrsForQuery.add("login like '"+email+"' AND ");
			 }
			 if(phone.length()>0){
			 listParametrsForQuery.add("phone like '"+phone+"' AND ");
			 }
			 listParametrsForQuery.add("registerDay between '"+registrDateStart+"' AND '"+registrDateEnd+"' ");
		 return listParametrsForQuery;
	}
	
	 public String makeQueryForSearch(List<String> listParams){
		 StringBuffer newQuery=new StringBuffer();
		 for(String param:listParams)
		 {newQuery.append(param);}
		 return newQuery.toString();
	 }
	
}
